import oauth2Manager from '@/core/oauth2/manager/oauth2Manager'
import accountProfileManager from '@/core/account/manager/accountProfileManager'
import useAccountBaseInfoStore from '@/core/account/store/useAccountBaseInfoStore'
import useAccountTokenInfoStore from '@/core/account/store/useAccountTokenInfoStore'
import useRememberMeLoginInfoStore from '@/core/auth/store/useRememberMeLoginInfoStore'
import useAccountTokenUserInfoStore from '@/core/account/store/useAccountTokenUserInfoStore'
import Oauth2TokenInfoDto from '@/core/oauth2/types/model/dto/Oauth2TokenInfoDto'
import LoginByPasswordRequest from '@/core/oauth2/types/model/request/LoginByPasswordRequest'
import globalConfig from '@/core/framework/config/globalConfig'

class AuthService {
	logout = async (): Promise<void> => {
		await oauth2Manager.logout()
		console.log('清除远程登录信息')
		useAccountTokenInfoStore.setState({}, true)
		useAccountBaseInfoStore.setState({}, true)
		useAccountTokenUserInfoStore.setState({}, true)
		console.log('清除本地登录信息')
		return
	}

	loginByUsernameAndPassword = async (params: LoginByPasswordRequest): Promise<void> => {
		const oauth2TokenInfo = await oauth2Manager.getTokenByPasswordGrantType(params)

		await this.loginByToken(oauth2TokenInfo)
	}

	logoutConfirm() {
		// const { t } = useI18n();
		// ElMessageBox.confirm(t("common.loginOutMessage"), t("common.reminder"), {
		// 	confirmButtonText: t("common.ok"),
		// 	cancelButtonText: t("common.cancel"),
		// 	type: "warning"
		// })
		// 	.then(async () => {
		// 		await this.logout();
		// 		await router.replace("/login");
		// 	})
		// 	.catch(() => {});
	}

	setRememberMeLoginInfo = async (params: { isRememberMe: boolean; username: string; password: string }) => {
		// 是否记住我
		if (params.isRememberMe) {
			useRememberMeLoginInfoStore.setState({
				username: params.username,
				password: params.password,
			})
		} else {
			useRememberMeLoginInfoStore.setState(null)
		}
	}

	private loginByToken = async (oauth2TokenInfo: Oauth2TokenInfoDto) => {
		const oauth2Introspect = await oauth2Manager.introspectByClient(
			oauth2TokenInfo.accessToken,
			globalConfig.accountClientId,
			globalConfig.accountClientSecret,
		)

		const oauth2UserInfo = oauth2Manager.convertOauth2UserInfoFromOauth2IntrospectResponse(oauth2Introspect)

		const userBaseInfo = await accountProfileManager.getUserBaseInfo(oauth2TokenInfo.accessToken)

		useAccountTokenInfoStore.setState(oauth2TokenInfo)
		useAccountTokenUserInfoStore.setState(oauth2UserInfo)
		useAccountBaseInfoStore.setState(userBaseInfo)
	}
}

export default new AuthService()
